%% Application of the Golden Search Method

%The function who's zero crossing we are trying to find
f=@(x) (x-3).^2;

%The Golden Ratio b/a
Phi=(1+sqrt(5))/2;

%a/(a+b) This is useful in calculations
R=1/(1+Phi);

%Setup our intial intrvals
X(1)=0;
X(3)=10;
X(2)=(X(3)-X(1))*R+X(1);

%Calculate function at these positions
F=f(X);

%Set toleerance for convergence.  
TolX=10*eps;

IntSize=X(3)-X(1);

%We can calculate how many iterations are needed
RB=(1-R)
% IntSize*RB^N=TolX
NIterRequired=log(TolX/IntSize)/log(RB)

%Setup the iterative loop and run until convergence
Cnt=1;
while IntSize>TolX
    [X,F] = GoldenSearch(X,F,f);
    IntSize=X(3)-X(1);
    Cnt=Cnt+1;
end

fprintf('Our zero crossing is at: %g\n',X(1))


%% Calculting pi

%In class, we explored a few ways of calculting pi.  Here is one:

%web('https://en.wikipedia.org/wiki/Gauss%E2%80%93Legendre_algorithm')

A=1
B=1/sqrt(2)
T=1/4
P=1

while abs(A-B)>eps
    AOld=A;
    BOld=B;
    A=(AOld+BOld)/2
    B=sqrt(AOld*BOld)
    T=T-P*(A-AOld)^2;
    P=2*P;
end

PI = (A+B)^2/(4*T)
PI-pi


